<?php
abstract class DAO {

    protected $dbh;//handler de DB

    public function __construct() {
        try {
            $this->dbh = SPDO::singleton();
        }
        catch(Exception $e) {
            throw $e;
        }
    }

    public function save($objetoTO) {
        try {
            if($objetoTO->getId() === NULL) {//si el objeto no tiene PK -> insertar
                $this->insert($objetoTO);
            }
            else {//si existe PK -> actualizar
                $this->update($objetoTO);
            }
        }
        catch(Exception $e) {
            throw $e;
        }
    }

    abstract public function load($objetoTO);

    abstract public function delete($id);

    abstract protected function update($objetoTO);

    abstract protected function insert($objetoTO);

    protected function count($table, $atribute, $condicion) {
        try {
            $query = "SELECT COUNT(".$atribute.") AS rows FROM ".$table;
            if($condicion!=""){
                $query .= " WHERE ".$condicion;
            }
            
            //echo "<br/>".$query."<br/>";
            $stmt = $this->dbh->prepare($query);
            $stmt->setFetchMode(PDO::FETCH_OBJ);
            $stmt->execute();
            return $stmt->fetchColumn();
        }catch (Exception $e) {
            throw $e;
        }
    }

}
?>